package com.jun.util;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.OutputStream;

/**
 * 二维码工具
 *
 */
@Slf4j
public class QRCodeUtil {

  private static final QrConfig QR_CONFIG = new QrConfig(300, 300);
  private static final String LOCAL_PATH =  System.getProperty("user.dir") + "\\qrcode\\";
  private static final String SUFFIX = ".png";

  /**
   * 生成二维码到本地
   * @param content 二维码内容
   * @param fileName 二维码名字(不带后缀)
   */
  public static File generateQRCodeToLocal(String content, String fileName) {
    try {
      File generate = QrCodeUtil.generate(content, QR_CONFIG,
          new File(LOCAL_PATH + fileName + SUFFIX));
      log.info("二维码生成到本地:" + LOCAL_PATH + fileName + SUFFIX);
      return generate;
    } catch (Exception e) {
      e.printStackTrace();
      log.info("二维码生成到本地: 失败");
    }
    return null;
  }

  public static String getBase64QRCodeOnLocal(Integer orderId) {
    File file = new File(LOCAL_PATH + orderId + SUFFIX);
    return Base64Encoder.encode(FileUtil.readBytes(file));
  }

}
